import { loginAPI } from '@/api'

const state = {
  token: localStorage.getItem('token') || '',
  refresh_token: localStorage.getItem('refresh_token') || ''
}

const mutations = {
  SETTOKEN (state, token) {
    state.token = token
    localStorage.setItem('token', token)
  },
  SETREFRESHTOKEN (state, refresh_token) {
    state.refresh_token = refresh_token
    localStorage.setItem('refresh_token', refresh_token)
  }
}

const actions = {
  async asyncLoginAction (store, val) {
    try {
      const res = await loginAPI(val)
      const { token, refresh_token } = res.data.data
      store.commit('SETTOKEN', token)
      store.commit('SETREFRESHTOKEN', refresh_token)
      return Promise.resolve(res) // 返回成功的Promise对象
    } catch (err) {
      return Promise.reject(err) // 返回失败的Promise对象
    }
  }
}

export default {
  state,
  mutations,
  actions
}
